package com.heima.article.intercoller;

import com.heima.article.utils.AppUserThreadLocalUtil;
import com.heima.model.user.entity.ApUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class WebTokenInterceptor extends HandlerInterceptorAdapter {


    /**
     * 前置拦截，目标控制器执行之前执行拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求中的用户ID userid
        String userId = request.getHeader("userId");
        //通过网关服务
        if (StringUtils.isNotBlank(userId) && "0".equals(userId)) {
            //2.将用户信息保存到threadLocal
            ApUser apUser = new ApUser();
            apUser.setId(Long.valueOf(userId));

            AppUserThreadLocalUtil.set(apUser);
            return super.preHandle(request, response, handler);
        }

        //没有经过网关进行权限验证，返回401，以及失败信息

        return true;
    }

    /**
     * 后置拦截，目标控制器执行之后拦截
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        //清空thread local数据，防止内存泄漏
        AppUserThreadLocalUtil.remove();

        super.postHandle(request, response, handler, modelAndView);
    }
}
